#!/bin/sh

# if app not exist
if [ ! -f /bin/inetd ]; then
    exit 0
fi

LOG="logger -t inetd"

start() {
    get_param
    if [ "$Login" != "" ]; then
	echo > /etc/inetd.conf
	need_start=0
	if [ -f /bin/dropbear ] && [ "$RemoteSSH" != "" ] && [ "$RemoteSSH" != "0" ]; then
	    echo "ssh stream tcp nowait $Login /bin/dropbear /bin/dropbear -i -K60 -I360 -m" >> /etc/inetd.conf
	    need_start=1
	fi
	if [ -f /bin/ftpd ] && [ "$RemoteFTP" != "" ] && [ "$RemoteFTP" != "0" ]; then
		if [ "$FtpIdleTime" != "" ]; then
			echo "$FtpPort stream tcp nowait $Login /bin/ftpd ftpd -wS -t $FtpIdleTime $FtpRootDir" >> /etc/inetd.conf
		else
			echo "$FtpPort stream tcp nowait $Login /bin/ftpd ftpd -wS $FtpRootDir" >> /etc/inetd.conf
		fi
	    need_start=1
	fi
	if [ -f /bin/telnetd ] && [ "$RemoteTelnet" != "" ] && [ "$RemoteTelnet" != "0" ]; then
	    echo "telnet stream tcp nowait $Login /bin/telnetd telnetd -i" >> /etc/inetd.conf
	    need_start=1
	fi
	if [ "$need_start" = "1" ]; then
	    $LOG "Starting inetd"
    	    inetd -R 30 -q 64
	fi
    fi
}

get_param() {
    eval `nvram_buf_get 2860 Login RemoteSSH RemoteFTP FtpPort FtpRootDir FtpIdleTime RemoteTelnet`
}

stop() {
 $LOG "Stopping inetd"
    killall -q inetd
    killall -q -SIGKILL inetd
}

case "$1" in
	start)
	    start
	    ;;

	stop)
	    stop
	    ;;

	restart)
	    stop
	    start
	    ;;

	*)
	    echo $"Usage: $0 {start|stop|restart}"
	    exit 1
esac
